package com.ssyc.student.activity;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.github.aakira.expandablelayout.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.MediaPlayerManager;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.student.R;
import com.ssyc.student.adapter.StVocablaryPreviewRvAdapter;
import com.ssyc.student.bean.CloneWordPrepareInfo;
import com.ssyc.student.bean.WordPrepareInfo;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--金牌金概念2--题型选择--词汇预习界面
 * Created by Administrator on 2018/5/11 0011.
 */

public class StudentVocabularyPreviewActivity extends BaseActivity implements View.OnClickListener {

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //LessonId
    private String lessonId;

    //GradeId
    private String gradeId;

    //加载视图
    private RelativeLayout rlLoadingView;

    //返回图标
    private ImageView ivBack;

    //列表适配器
    private RecyclerView rv;

    //列表的数据集合
    private List<WordPrepareInfo.DataBean.QuestionListBean> oldDatas;

    //复制的clone数据,由于TimeInterpolator插值器不能传递
    private List<CloneWordPrepareInfo.DataBean.QuestionListBean> cloneDatas;

    //下拉刷新控件
    private SmartRefreshLayout srf;

    //空视图
    private View emptyView;


    //用于上传服务器记录时间的id
    private String rowId;
    public static String ENERGY;

    //列表适配器对象
    private StVocablaryPreviewRvAdapter adapter;

    {
        //初始化计时器对象
        TimeCount.init();
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_vocabulary_prepare;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //获取传递过来的LessonId
        initIntent();

        //初始化下拉刷新
        initSrf();

        //获取页面数据
        http();

    }


    /**
     * 初始化控件的方法
     */
    public void initView() {
        rlLoadingView = findViewById(R.id.rl_loading_view);
        rlLoadingView.setVisibility(View.VISIBLE);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        rv = findViewById(R.id.rv);
        srf = findViewById(R.id.srf);
    }

    /**
     * 获取传递过来的对象
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);
    }


    /**
     * 初始化下拉刷新控件
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, null);
    }


    /**
     * 获取页面数据的方法
     */
    private void http() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("type", "20");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lesson", "Lesson" + lessonId);
        map.put("examtype", "10");
        map.put("role", AccountUtils.getRole(this));
        Log.i("test", "url--" + HttpAdress.VOCABULARYPREVIEW + "?" + "type=20&examtype=10&role=2&acc=" + AccountUtils.getAccount(this)
                + "&role=" + AccountUtils.getRole(this)+"&lesson=Lesson"+lessonId);
        HttpUtils.post(HttpAdress.VOCABULARYPREVIEW, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoadingView) {
                    rlLoadingView.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (null != rlLoadingView) {
                    rlLoadingView.setVisibility(View.GONE);
                }

                WordPrepareInfo info = null;

                CloneWordPrepareInfo cloneInfo = null;

                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, WordPrepareInfo.class);
//                        Log.i("test",response);
                        LogUtils.iTag("test",response);

                        cloneInfo = GsonUtil.jsonToBean(response, CloneWordPrepareInfo.class);

                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                }

                //获取clone数据
                if (null != cloneInfo) {
                    if ("200".equals(cloneInfo.getState())) {
                        CloneWordPrepareInfo.DataBean data = cloneInfo.getData();
                        if (null != data) {
                            cloneDatas = data.getQuestion_list();
                        }
                    } else {
                        //服务器返回异常状态码
                        UiUtils.Toast("服务器异常", false);
                        Log.i("test", "返回异常码是:" + info.getState());
                    }
                }


                if (null != info) {
                    if ("200".equals(info.getState())) {
                        WordPrepareInfo.DataBean data = info.getData();
                        if (null != data) {
                            //获取数据集合
                            oldDatas = data.getQuestion_list();
                            //添加动画资源
                            if (null != oldDatas && oldDatas.size() != 0) {
                                for (int i = 0; i < oldDatas.size(); i++) {
                                    oldDatas.get(i).setInterpolator(Utils.createInterpolator(Utils.LINEAR_OUT_SLOW_IN_INTERPOLATOR));
                                }
                            }
                            //设置列表适配器
                            initRv();
                        }
                    } else {
                        //服务器返回异常状态码
                        UiUtils.Toast("服务器异常", false);
                        Log.i("test", "返回异常码是:" + info.getState());
                    }
                }
            }
        });
    }

    /**
     * 设置列表适配器的方法
     */
    private void initRv() {
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        emptyView.setBackgroundColor(getResources().getColor(R.color.coffeebg));
        adapter = new StVocablaryPreviewRvAdapter(lessonId, gradeId, this, R.layout.student_rv_word_preview, oldDatas, cloneDatas);
        BqaManager.setRv(emptyView, this, adapter, rv);
    }


    /**
     * 页面控件点击事假
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        }
    }

    /**
     * 该生命周期内请求服务器记录初次进入的时间
     */
    @Override
    protected void onResume() {
        super.onResume();
        RecordTimeUtil.httpEnterTime(this, lessonId, gradeId, "10", new RecordTimeUtil.onRecordRowIdListener() {
            @Override
            public void recordRowId(String id, String en) {
                rowId = id;
                ENERGY = en;
            }
        });
    }

    /**
     * 切换页面的时候暂停播放录音
     */
    @Override
    protected void onPause() {
        super.onPause();
        MediaPlayerManager.getInstance().stop();

        long time = System.currentTimeMillis() - TimeCount.newInstance().getLastTime();

        //计算总用时
        long totalTime = TimeCount.newInstance().getTotalTime() + time;

        //记录总用时
        TimeCount.newInstance().setTotalTime(totalTime);

        //上传服务器记录时间的接口
        RecordTimeUtil.httpExitTime(rowId, this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ENERGY = "";
    }

    /**
     * 同步收藏状态的消息处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        if (null != busInfo && 0x120 == busInfo.getType()) {
            if (0 == oldDatas.get(busInfo.getPos()).getCollection()) {
                oldDatas.get(busInfo.getPos()).setCollection(1);
            } else if (1 == oldDatas.get(busInfo.getPos()).getCollection()) {
                oldDatas.get(busInfo.getPos()).setCollection(0);
            }
            adapter.notifyDataSetChanged();
        } else if (StudentVocabularyPrepareSecondActivity.CLOSE == busInfo.getType()) {
            //收到当前页面关闭的消息了
            finish();
        }
        super.busEvent(busInfo);
    }

    /**
     * 考虑亮屏
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        //重置LastTime
        TimeCount.newInstance().setLastTime(System.currentTimeMillis());
    }
}
